package org.example.springcloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.springcloud.entities.Payment;
import org.example.springcloud.utils.ResultVOUtil;
import org.example.springcloud.vo.ResultVO;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Slf4j
@RestController
@RequestMapping("customer")
public class OrderController {
    //    public static final String PAYENT_URL = "http://localhost:8001";
    public static final String PAYENT_URL = "http://CLOUD-PAYMENT-SERVICE";
    @Resource
    private RestTemplate restTemplate;

    @GetMapping("payment/create")
    public ResultVO<?> create(Payment payment) {
        return restTemplate.postForObject(PAYENT_URL + "/payment/create", payment, ResultVO.class);
    }

    @GetMapping("payment/get/{id}")
    public ResultVO<?> getPayment(@PathVariable("id") long id) {
        return restTemplate.getForObject(PAYENT_URL + "/payment/get/" + id, ResultVO.class);
    }

    @GetMapping("payment/getForEntity/{id}")
    public ResultVO<?> getForEntity(@PathVariable("id") long id) {
//        return restTemplate.getForEntity(PAYENT_URL + "/payment/get/" + id, ResultVO.class);
        ResponseEntity<ResultVO> forEntity = restTemplate.getForEntity(PAYENT_URL + "/payment/get/" + id, ResultVO.class);
        if (forEntity.getStatusCode().is2xxSuccessful()) {
            log.info(forEntity.getStatusCode() + "\t" + forEntity.getHeaders());
            return ResultVOUtil.success(forEntity.getBody());
        } else {
            return ResultVOUtil.error();
        }
    }

    //查看服务信息
//    @GetMapping("payment/lb")
//    public String getPaymentLB() {
//        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
//        if (instances == null || instances.size() == 0) {
//            return null;
//        }
//        ServiceInstance serviceInstance = loadBalaner.instance(instances);
//        URI uri = serviceInstance.getUri();
//        System.out.println(uri+"/payment/lb");
//        return restTemplate.getForObject(uri+"/payment/lb",String.class);
////        return uri+"/payment/lb";
//    }

    // ====================> zipkin+sleuth
    @GetMapping("/payment/zipkin")
    public String paymentZipkin() {
        return restTemplate.getForObject(PAYENT_URL + "/payment/payment/zipkin/", String.class);
    }


}
